﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace GarminUploader.Connector
{
    public abstract class BaseConnector
    {
        // The client
        protected HttpClient client;

        // The base URL of the server
        protected abstract string baseUrl { get; }

        // Flags if user is logged in or not
        public bool loggedIn = false;

        protected BaseConnector()
        {
            // Set up the handler
            HttpClientHandler handler = new HttpClientHandler();
            handler.UseCookies = true;
            handler.UseDefaultCredentials = true;
            handler.AllowAutoRedirect = false;

            // Set up proxy (if required)
            if (WebRequest.DefaultWebProxy != null)
            {
                handler.Proxy = WebRequest.DefaultWebProxy;
                handler.UseProxy = true;
                handler.UseDefaultCredentials = true;
                WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultNetworkCredentials;
            }

            // Create the client with the base URL
            client = new HttpClient(handler);
            client.BaseAddress = new Uri(baseUrl);
        }

        // Required methods
        public abstract void login(string username, string password);
        public abstract List<DateTime> listActivityStartTimes();
        public abstract void upload(FitFile file);

        protected void checkLogin()
        {
            // Throw error if user isn't logged in
            if (!loggedIn)
            {
                throw new UserNotLoggedInException();
            }
        }
    }
}
